/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.metadata.rtcustomization.servermanager.repository;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.inspur.edp.lcm.metadata.api.entity.MetadataPackage;
import com.inspur.edp.lcm.metadata.common.ServiceUtils;
import com.inspur.edp.lcm.metadata.common.FileServiceImp;
import com.inspur.edp.metadata.rtcustomization.api.exception.ErrorCodes;
import com.inspur.edp.metadata.rtcustomization.api.exception.LcmMetadataException;
import com.inspur.edp.metadata.rtcustomization.api.exception.LcmParseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.*;

@Slf4j
public class MetadataPackageRepoService {

    public Map<String, MetadataPackage> getMetadataPackagesRecursivly(String path) {
        // 获取目录下所有的元数据包文件
        if (!StringUtils.hasLength(path)) {
            throw new LcmMetadataException(ErrorCodes.ECP_METADATA_0003, "path");
        }
        List<File> mdpkgs = FileServiceImp.listAllFiles(new File(path), pathname -> pathname.getPath().endsWith(ServiceUtils.getMetadataPackageExtension()));

        // 解析元数据包
        if (mdpkgs == null || mdpkgs.size() == 0) {
            return null;
        }
        Map<String, MetadataPackage> mdpkgMap = new HashMap<>();
        ObjectMapper mapper = ServiceUtils.getMapper();
        for (File mdpkg : mdpkgs) {
            Map<String, String> manifestMap = ServiceUtils.readCompressedFile(mdpkg, ServiceUtils.getManifestFileName());
            MetadataPackage metadataPackage;
            try {
                metadataPackage = mapper.readValue(manifestMap.get(ServiceUtils.getManifestFileName()), MetadataPackage.class);
            } catch (JsonProcessingException e) {
                throw new LcmParseException(e, ErrorCodes.ECP_PARSE_0006, mdpkg.getAbsolutePath());
            }
            mdpkgMap.put(mdpkg.getAbsolutePath(), metadataPackage);
        }
        return mdpkgMap;
    }
}
